package com.guigu.erp.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.erp.dto.ManufactureManufactureDto;
import com.guigu.erp.mapper.ManufactureManufactureMapper;
import com.guigu.erp.pojo.*;
import com.guigu.erp.service.*;
import com.guigu.erp.utils.PageUtils;
import com.guigu.erp.vo.ManufactureApplyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Service
public class ManufactureManufactureServiceImpl extends ServiceImpl<ManufactureManufactureMapper, ManufactureManufacture>
        implements ManufactureManufactureService {

    @Autowired
    private ManufactureManufactureMapper manufactureManufactureMapper;

    @Autowired
    private ManufactureApplyService manufactureApplyService;

    @Autowired
    private ManufactureProcedureModuleService manufactureProcedureModuleService;

    @Autowired
    private ManufactureDesignProcedureModuleService manufactureDesignProcedureModuleService;

    @Autowired
    private ManufactureProcedureService manufactureProcedureService;

    @Override
    public String getMaxFlowNumber() {
        ManufactureManufacture maxFile = manufactureManufactureMapper.queryMaxFile();
        if (maxFile == null) {
            return null;
        }
        String manufactureId = maxFile.getManufactureId();
        return manufactureId;
    }

    @Override
    @Transactional
    public boolean addManufactured(ManufactureManufactureDto dto) {

        boolean flag=false;
        // 1.修改生产计划表派工标志位
        //拿出生产计划表的id
        int[] ary = dto.getAry();
        dto.setTestedAmount(new BigDecimal(0));
        //循环遍历修改派工单标志位
        for (int i = 0; i < ary.length; i++) {
            ManufactureApply apply = manufactureApplyService.getById(ary[i]);
            apply.setManufactureTag("P001-1");
            manufactureApplyService.updateById(apply);
        }

        // 2.生产总表添加数据
        //设置 APPLY_ID_GROUP 生产计划序号组
        StringBuffer buffer = new StringBuffer();
        if (ary.length == 1) {
            ManufactureApply byId = manufactureApplyService.getById(ary[0]);
            buffer.append(byId.getApplyId());
            dto.setApplyIdGroup(buffer.toString());
        }
        if (ary.length > 1) {
            for (int i = 0; i < ary.length; i++) {
                ManufactureApply apply = manufactureApplyService.getById(ary[i]);
                buffer.append(apply.getApplyId());
                dto.setApplyIdGroup(buffer.append("/").toString());
            }
        }


        //设置标志位
        dto.setCheckTag("S001-0");
        dto.setManufactureProcedureTag("S002-0");

        BigDecimal total = new BigDecimal(0);
        BigDecimal num = new BigDecimal(0);

        // 3.生产工序表添加数据
        List<ManufactureDesignProcedureDetails> details = dto.getDetails();
        for(int i=0;i<details.size();i++){
            ManufactureDesignProcedureDetails procedureDetails = details.get(i);
            QueryWrapper<ManufactureDesignProcedureModule> wrapper = new QueryWrapper<>();
            wrapper.eq("PARENT_ID", procedureDetails.getId());
            List<ManufactureDesignProcedureModule> list = manufactureDesignProcedureModuleService.list();
            for(int j=0;j<list.size();j++){
                ManufactureDesignProcedureModule d = list.get(j);
                if(procedureDetails.getId().equals(d.getParentId())){
                    BigDecimal n1=procedureDetails.getLabourHourAmount().multiply(d.getCostPrice());
                    total=total.add(n1);
                }
            }
            //获取工时成本
            BigDecimal price = procedureDetails.getSubtotal();
            num = num.add(price);
        }
        //设置工时总成本
        dto.setLabourCostPriceSum(num);
        //设置物料总成本
        dto.setModuleCostPriceSum(total);
        //设置实际工时总成本
        dto.setRealLabourCostPriceSum(new BigDecimal(0));
        //设置实际物料总成本
        dto.setRealModuleCostPriceSum(new BigDecimal(0));
        this.save(dto);


        for (int i = 0; i < details.size(); i++) {
            ManufactureDesignProcedureDetails procedureDetails = details.get(i);

            QueryWrapper<ManufactureDesignProcedureModule> wrapper = new QueryWrapper<>();
            wrapper.eq("PARENT_ID", procedureDetails.getId());
            List<ManufactureDesignProcedureModule> list = manufactureDesignProcedureModuleService.list();



            ManufactureProcedure procedure = new ManufactureProcedure();
            //设置父id
            procedure.setParentId(dto.getId());
            //设置工序完成标志
            procedure.setProcedureFinishTag("G004-0");
            //设置工序交接标志
            procedure.setProcedureTransferTag("G005-0");
            //设置物料成本
            procedure.setModuleSubtotal(total);
            //设置工序名称
            procedure.setProcedureName(procedureDetails.getProcedureName());
            //设置工序编号
            procedure.setProcedureId(procedureDetails.getProcedureId());
            //设置序号
            procedure.setDetailsNumber(i+1);
            //设置设计工时数
            procedure.setLabourHourAmount(procedureDetails.getLabourHourAmount());
            //设置工时成本
            procedure.setSubtotal(procedureDetails.getSubtotal());
            //设置实际工时数
            procedure.setRealLabourHourAmount(new BigDecimal(0));
            //设置实际工时成本
            procedure.setRealModuleSubtotal(new BigDecimal(0));
            //设置实际工时成本
            procedure.setRealSubtotal(new BigDecimal(0));
            //设置工序合格数量
            procedure.setRealAmount(new BigDecimal(0));
            BigDecimal totalPrice = new BigDecimal(0);
            for (int z=0;z<list.size();z++){
                if (procedureDetails.getId().equals(list.get(z).getParentId())) {
                    ManufactureDesignProcedureModule manufactureDesignProcedureModule = list.get(z);
                    BigDecimal n = procedureDetails.getLabourHourAmount().multiply(manufactureDesignProcedureModule.getCostPrice());
                    totalPrice=totalPrice.add(n);
                }
            }
            //设置物料成本
            procedure.setModuleSubtotal(totalPrice);
            manufactureProcedureService.save(procedure);



            // 4.生产工序明细添加数据
            for (int j = 0; j < list.size(); j++) {
                if (procedureDetails.getId().equals(list.get(j).getParentId())) {
                    ManufactureDesignProcedureModule procedureModule = list.get(j);

                    ManufactureProcedureModule module = new ManufactureProcedureModule();
                    //设置父级id
                    module.setParentId(procedure.getId());
                    //设置工序物料序号
                    module.setDetailsNumber(j + 1);
                    //设置设计数量
                    module.setAmount(procedureModule.getAmount().multiply(procedureDetails.getLabourHourAmount()));
                    //设置产品名称
                    module.setProductName(procedureModule.getProductName());
                    //设置产品编号
                    module.setProductId(procedureModule.getProductId());
                    //设置物料单价
                    module.setCostPrice(procedureModule.getCostPrice());
                    //设置物料小计
                    module.setSubtotal(procedureDetails.getLabourHourAmount().multiply(procedureModule.getCostPrice()));
                    //设置实际使用数量
                    module.setRealAmount(new BigDecimal(0));
                    //设置实际物料成本
                    module.setRealSubtotal(new BigDecimal(0));
                    BigDecimal temp = module.getSubtotal();
                    total = total.add(temp);
                    flag = manufactureProcedureModuleService.save(module);
                }
            }
        }
        return flag;
    }

    @Override
    public PageUtils<ManufactureManufacture> getAll(ManufactureApplyVo vo, Integer pageNo, Integer pageSize) {
        QueryWrapper<ManufactureManufacture> wrapper = new QueryWrapper<>();
        if (vo!=null){
            if(!StringUtils.isEmpty(vo.getSearch_id())){
                wrapper.like("MANUFACTURE_ID","%"+vo.getSearch_id()+"%");
            }
            if(!StringUtils.isEmpty(vo.getSearch_name())){
                wrapper.like("PRODUCT_NAME","%"+vo.getSearch_name()+"%");
            }
            if(!StringUtils.isEmpty(vo.getSearch_state())){
                wrapper.eq("CHECK_TAG",vo.getSearch_state());
            }
            if(!StringUtils.isEmpty(vo.getSearch_time1())){
                wrapper.ge("REGISTER_TIME",vo.getSearch_time1());
            }
            if(!StringUtils.isEmpty(vo.getSearch_time2())){
                wrapper.le("REGISTER_TIME",vo.getSearch_time2());
            }
        }
        PageHelper.startPage(pageNo,pageSize);
        List<ManufactureManufacture> list = this.list(wrapper);
        PageInfo<ManufactureManufacture> pageInfo = new PageInfo<>(list);
        PageUtils<ManufactureManufacture> pageUtils = new PageUtils<>();
        pageUtils.setRows(pageInfo.getList());
        pageUtils.setTotal(pageInfo.getTotal());
        return pageUtils;
    }
}
